package grape.common.rest.common;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.json.JSONUtil;
//import grape.auth.rest.client.auth.AuthClient;
import grape.common.AbstractLoginUser;
import grape.common.rest.security.GrapeJwtAccessTokenConverter;
import grape.common.rest.tools.RequestTool;
import grape.common.service.common.dataconstraint.RawDataConstraint;
import grape.common.service.loginuser.GrapeUserDetails;
import grape.common.service.loginuser.LoginUser;
import grape.common.tools.MDCTool;
import grape.common.tools.RequestIdTool;
import grape.common.tools.ThreadContextTool;
import grape.common.tools.ToolService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 全局拦截
 * Created by yangwei
 * Created at 2019/9/27 15:46
 */
@Slf4j
public class GlobalInterceptor extends HandlerInterceptorAdapter implements ToolService {

    // 计时器key
    public static final String timeStartKey = "timeStartKey";
    // 记录是否有异常key
    public static final String hasExceptionKey = "hasExceptionKey";
    /**
     * Authorization认证开头是"bearer "
     */
    private static final String BEARER = "Bearer ";
    // 该bean配置在 grape.common.rest.CommonRestSecurityConfig.accessTokenConverter
    // 目的是可以通用accessToken校验
    @Autowired
    GrapeJwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 初始化请求id
        String requestId = RequestIdTool.initRequestId(request.getHeader(RequestIdTool.reqeustIdKey));
        MDC.put(MDCTool.tranceId,requestId);
        long start = System.currentTimeMillis();
        ThreadContextTool.put(timeStartKey,start);
        // 尝试认证用户
        tryAuthentication(request, response);


        GrapeUserDetails loginUser = AbstractLoginUser.getLoginUser();
        String userId = null;
        String username = null;
        if (loginUser != null) {
            userId = loginUser.userId();
        }
        log.info("请求开始: userId=[{}],username=[{}],requestUrl=[{}{}] ,requestMethod=[{}],requestIp=[{}]",
                 userId,username,request.getRequestURL(),request.getQueryString() == null? "":"?" + request.getQueryString(),request.getMethod(), RequestTool.getRemoteAddr(request));
        if(handler instanceof HandlerMethod){
            Object annotationValue = AnnotationUtil.getAnnotationValue(((HandlerMethod) handler).getMethod(), ApiOperation.class);
            log.info("请求接口名称: apiName=[{}],method=[{}]",
                     annotationValue,((HandlerMethod) handler).toString());
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 全局拦截完成处理
     * 这里一般不会有异常传过来，因为所有的异常都被grape.common.rest.advice.GlobalExceptionAdvice拦截处理
     * 如果这里有异常说明全局拦截异常处理没有关注该异常
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {


        String msg = "{}: requestUrl=[{}{}] ,duration=[{}]ms";
        String msgHit = "请求正常结束";
        long start = (long) ThreadContextTool.get(timeStartKey);

        Boolean hasExceptionInGlobalExceptionAdvice = ((Boolean) ThreadContextTool.get(hasExceptionKey));
        if (ex != null || (hasExceptionInGlobalExceptionAdvice != null && hasExceptionInGlobalExceptionAdvice)) {
            msgHit = "请求异常结束";
        }
        long interval = System.currentTimeMillis() - start;
        log.info(msg,msgHit,request.getRequestURL(),request.getQueryString() == null? "":"?" + request.getQueryString(),interval);


        ThreadContextTool.remove();
        super.afterCompletion(request, response, handler, ex);
    }

    /**
     *
     * @param request
     * @param response
     */
    private void tryAuthentication(HttpServletRequest request, HttpServletResponse response){
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            // 如果没有被认证，尝试认证
            if (authentication == null || !authentication.isAuthenticated()) {
                String headerAuth = request.getHeader(HttpHeaders.AUTHORIZATION);
                if(!isStrEmpty(headerAuth)){

                    if(isStrStart(headerAuth,BEARER)){
                        log.debug("请求头中含有认证BEARER 尝试认证[{}]：headerAuth=[{}]",BEARER,headerAuth);

                        String accessToken = headerAuth.substring(BEARER.length());

                        Map<String, ?> checkTokenResult = jwtAccessTokenConverter.decodePublic(accessToken);
                        OAuth2AccessToken oAuth2AccessToken = jwtAccessTokenConverter.extractAccessToken(accessToken, checkTokenResult);
                        if (oAuth2AccessToken.isExpired()) {
                            throw new InvalidTokenException("Token has expired");
                        }
                        String userId = (String) checkTokenResult.get("user_name");
                        List<String> authorities = (List) checkTokenResult.get("authorities");
                        String identifierType = ((String) checkTokenResult.get("user_name_type"));
                        Object data_scopes = checkTokenResult.get("data_scopes");
                        List<RawDataConstraint> rawDataConstraints = new ArrayList<>();
                        if (data_scopes != null) {
                            List dataScopes = ((List) data_scopes);
                            if (!isEmpty(dataScopes)) {
                                rawDataConstraints = JSONUtil.toList(JSONUtil.parseArray(JSONUtil.parseArray(data_scopes)), RawDataConstraint.class);
                            }
                        }
                        LoginUser userDetails = createUser(userId, authorities,rawDataConstraints,identifierType);
                        // 设置登录用户方便获取
                        AbstractLoginUser.setLoginUser(userDetails);
                        UsernamePasswordAuthenticationToken token =
                                new UsernamePasswordAuthenticationToken(userId,
                                        "N/A",
                                        AuthorityUtils.createAuthorityList(authorities.toArray(new String[0])));
                        //token.setDetails(authentication.getDetails());
                        SecurityContextHolder.getContext().setAuthentication(token);
                        log.debug("尝试认证[{}]成功：headerAuth=[{}]",BEARER,headerAuth);
                    }

                }
            }
        }catch (Exception e){
            log.debug("尝试认证失败: ", e.getMessage());
        }
    }

    public LoginUser createUser(String userId,List<String> authorities,List<RawDataConstraint> rawDataConstraints,String identifierType) throws UsernameNotFoundException {
        boolean superAdmin = false;
        if (!isEmpty(authorities)) {
            String superAdminRoleCode = "ROLE_" + AbstractLoginUser.superadminCode;
            for (String authoritie : authorities) {
                if (isEqual(authoritie, superAdminRoleCode)) {
                    superAdmin = true;
                    break;
                }
            }
        }
        LoginUser loginUser = new LoginUser(userId,
                "N/A",
                true,
                true,
                true,
                true,
                AuthorityUtils.createAuthorityList(authorities.toArray(new String[0])),
                rawDataConstraints
        );
        loginUser.setId(userId);
        loginUser.setSuperAdmin(superAdmin);
        loginUser.setIdentifierTypeDictId(identifierType);
        return loginUser;
    }
}
